package com.zuo_book.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zuo_book.common.Result;
import com.zuo_book.common.SecurityUtils;
import com.zuo_book.entity.SysProjectMember;
import com.zuo_book.entity.User;
import com.zuo_book.mapper.UserMapper;
import com.zuo_book.service.SysProjectMemberService;
import com.zuo_book.service.SysProjectService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 项目成员控制器
 */
@Slf4j
@RestController
@RequestMapping("/project/member")
@RequiredArgsConstructor
public class SysProjectMemberController {

    private final SysProjectMemberService projectMemberService;
    private final SysProjectService projectService;
    private final UserMapper userMapper;

    /**
     * 添加项目成员
     */
    @PostMapping("/add")
    public Result<Long> addMember(@RequestBody SysProjectMember member) {
        // 检查当前用户是否有权限添加成员
        Long currentUserId = SecurityUtils.getCurrentUserId();
        Integer role = projectMemberService.getMemberRole(member.getProjectId(), currentUserId);
        if (role == null || role != 0) {
            return Result.fail("只有项目创建者才能添加成员");
        }

        Long memberId = projectMemberService.addMember(member);
        return Result.success(memberId);
    }

    /**
     * 更新项目成员
     */
    @PutMapping("/update")
    public Result<Void> updateMember(@RequestBody SysProjectMember member) {
        // 检查当前用户是否有权限更新成员
        Long currentUserId = SecurityUtils.getCurrentUserId();
        Integer role = projectMemberService.getMemberRole(member.getProjectId(), currentUserId);
        if (role == null || role != 0) {
            return Result.fail("只有项目创建者才能更新成员");
        }

        projectMemberService.updateMember(member);
        return Result.success();
    }

    /**
     * 删除项目成员
     */
    @DeleteMapping("/delete/{memberId}")
    public Result<Void> deleteMember(@PathVariable Long memberId) {
        // 获取成员信息
        SysProjectMember member = projectMemberService.getMemberById(memberId);

        // 检查当前用户是否有权限删除成员
        Long currentUserId = SecurityUtils.getCurrentUserId();
        Integer role = projectMemberService.getMemberRole(member.getProjectId(), currentUserId);
        if (role == null || role != 0) {
            return Result.fail("只有项目创建者才能删除成员");
        }

        projectMemberService.deleteMember(memberId);
        return Result.success();
    }

    /**
     * 获取项目成员详情
     */
    @GetMapping("/info/{memberId}")
    public Result<SysProjectMember> getMemberInfo(@PathVariable Long memberId) {
        SysProjectMember member = projectMemberService.getMemberById(memberId);
        return Result.success(member);
    }

    /**
     * 获取项目所有成员
     */
    @GetMapping("/list/{projectId}")
    public Result<List<Map<String, Object>>> getProjectMembers(@PathVariable Long projectId) {
        // 检查当前用户是否是项目成员
        Long currentUserId = SecurityUtils.getCurrentUserId();
        if (!projectMemberService.isProjectMember(projectId, currentUserId)) {
            return Result.fail("您不是该项目的成员");
        }

        // 获取项目成员
        List<SysProjectMember> members = projectMemberService.getProjectMembers(projectId);

        // 获取用户信息
        List<Long> userIds = members.stream().map(SysProjectMember::getUserId).collect(Collectors.toList());
        List<User> users = userMapper.selectBatchIds(userIds);
        Map<Long, User> userMap = users.stream().collect(Collectors.toMap(User::getId, user -> user));

        // 组装返回数据
        List<Map<String, Object>> result = members.stream().map(member -> {
            User user = userMap.get(member.getUserId());
            Map<String, Object> map = Map.of(
                "id", member.getId(),
                "userId", member.getUserId(),
                "projectId", member.getProjectId(),
                "roleType", member.getRoleType(),
                "joinTime", member.getJoinTime(),
                "username", user != null ? user.getUsername() : "",
                    "avatar", user != null ? user.getAvatar() : ""
            );
            return map;
        }).collect(Collectors.toList());

        return Result.success(result);
    }

    /**
     * 分页查询项目成员
     */
    @GetMapping("/page/{projectId}")
    public Result<Page<SysProjectMember>> pageProjectMembers(
            @PathVariable Long projectId,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        // 检查当前用户是否是项目成员
        Long currentUserId = SecurityUtils.getCurrentUserId();
        if (!projectMemberService.isProjectMember(projectId, currentUserId)) {
            return Result.fail("您不是该项目的成员");
        }

        Page<SysProjectMember> memberPage = projectMemberService.listProjectMembers(projectId, page, size);
        return Result.success(memberPage);
    }

    /**
     * 检查用户是否是项目成员
     */
    @GetMapping("/check/{projectId}")
    public Result<Boolean> checkProjectMember(@PathVariable Long projectId) {
        Long currentUserId = SecurityUtils.getCurrentUserId();
        boolean isMember = projectMemberService.isProjectMember(projectId, currentUserId);
        return Result.success(isMember);
    }

    /**
     * 获取用户在项目中的角色
     */
    @GetMapping("/role/{projectId}")
    public Result<Integer> getMemberRole(@PathVariable Long projectId) {
        Long currentUserId = SecurityUtils.getCurrentUserId();
        Integer role = projectMemberService.getMemberRole(projectId, currentUserId);
        return Result.success(role);
    }
}
